import Taro from '@tarojs/taro';
import { makeFacade as makeAuthFacade } from '@/facade/authFacade';
import { makeFacade as makeMsgFacade } from '@/facade/messageFacade';
import CONFIG from '@/config';
import { MessageItem } from "@/models/Message";
import { getAuthorization, isJSON } from '.';
import { getLogger } from './log';

export class Websocket {
  authFacade = makeAuthFacade();
  msgFacade = makeMsgFacade();

  reconnectTimes = 0;//这是重连的次数
  reconnectTimout = 5; // 这次每次重连的时间 默认为5秒之后
  setTimer: any = null; // 存放定时器  为了关闭用到的
  automaticClose = true; // 这里默认是客户端和服务器自动断开
  webSocket: any = null; //ws实例
  socketConnected = false; //webSocket连接状态
  logger = getLogger("/util/websocket");

  // constructor() {
  //    this.initWS();
  // }

  initWS(): void { // wbsocket逻辑
    if (this.webSocket) this.closeWebSocket(); // 先关 再开 避免多次重复连接

    const header = getAuthorization();
    this.webSocket = Taro.connectSocket({
      url: CONFIG.WS_ROOT,
      header: header || {},
    })
    Taro.onSocketOpen(res => { // 打开webSocket
      this.resetStatus();
      this.socketConnected = true;
      console.log('WebSocket连接已打开！', res)
    })

    Taro.onSocketMessage(res => { // 接收数据
      console.log(res);
      //TODO 后端封装好数据结构
      if (isJSON(res.data)) {
        const wsMsg: MessageItem = res.data;
        // messageStore.update(state => {
        //   state.wsMsg = wsMsg;
        // })
      }
    })
    Taro.onSocketError(() => {  //这里是监听链接出错
      this.reConnectWebSocket();
    })
    Taro.onSocketClose(res => { //监测webSocket关闭
      console.log("websocket关闭", res);
      this.socketConnected = false;
      this.automaticClose && this.reConnectWebSocket();  // 只有是自动断开时才开启重连 这判断挺重要
    })
  }

  closeWebSocket(): void { // 手动关闭webSocket
    this.webSocket.close({
      success() {
        this.webSocket = null;
        console.log('webSocket关闭成功')
      }
    })
  }

  reConnectWebSocket(): void {  // 重新连接webSocket
    clearTimeout(this.setTimer); // 先关闭定时器
    if (this.reconnectTimes <= 5) {
      this.reconnectTimes += 1; // 每次重连一次num递增1
      // reconnectTimout的值每次为 5 10 15 30 60
      this.setTimer = setTimeout(() => {
        this.reconnectTimes <= 3 ? this.reconnectTimout = this.reconnectTimes * 5 : this.reconnectTimout = this.reconnectTimout * 2;
        this.initWS()
      }, this.reconnectTimout * 1000)
    } else {
      //5次链接都失败走这里
      this.resetStatus();
      console.error("websocket连接失败超过5次");
    }
  }

  //重置状态, 恢复小程序websocket默认自动断开 初始化数据
  resetStatus(): void {
    this.automaticClose = true;
    this.reconnectTimes = 0;
    this.reconnectTimout = 5;
  }

  /* onShow() {
      this.setData({ automaticClose: true，this.reconnectTimes：0，this.reconnectTimout: 5 }) //
  }

  onHide() {
      this.setData({ automaticClose: false }) // 这一步其实是告诉小程序 这是用户手动断开websocket的, 这一步也判断是否需要重连webSocket的条件依据
  } */
}

export const websocket = new Websocket();
